#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <bitset>
#include <utility>
using namespace std;

#define mm(a, n) memset(a, n, sizeof a)
#define mk(a, b) make_pair(a, b)

const double eps = 1e-6;
const int INF = 0x3f3f3f3f;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef pair<int, LL> PIL;

inline void quickread() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
}

const int N = 1e6, M = 1e5 + 10;

struct Node {
    int address, data, next;

    bool operator < (const Node & n) const {
        return data < n.data;
    }
}node[N];

int n, start;

inline void solution() {
    cin >> n >> start;
    for (int i = 0; i < n; i ++ ) {
        int address;
        cin >> address;
        node[address].address = address;
        cin >> node[address].data >> node[address].next;
    }
    Node nodes[M];
    int idx = 0;
    while (start != -1) {
        nodes[idx].address = node[start].address;
        nodes[idx ++ ].data = node[start].data;
        start = node[start].next;
    }
    sort(nodes, nodes + n);
    cout << n << " " << nodes[0].address << endl;
    for (int i = 0; i < n - 1; i ++ ) 
        printf("%05d %d %05d\n", nodes[i].address, nodes[i].data, nodes[i + 1].address);
    printf("%05d %d -1\n", nodes[n - 1].address, nodes[n - 1].data);
    return;
}

int main() {
    freopen("input.txt", "r", stdin);
    quickread();
    solution();
    return 0;
}